package com.shm.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.Picture;
import com.ruoyi.common.core.domain.entity.Product;
import com.ruoyi.common.core.domain.vo.ProductVo;
import com.ruoyi.common.enums.PictureType;
import com.ruoyi.common.utils.DateUtils;
import com.shm.algorithm.GroupDivide;
import com.shm.service.IPictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shm.mapper.ProductMapper;
import com.shm.service.IProductService;

/**
 * 商品Service业务层处理
 *
 * @author dam
 * @date 2023-07-21
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
//    @Autowired
//    private ProductMapper productMapper;

    @Autowired
    private IPictureService pictureService;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public Product selectProductById(Long id) {
        return baseMapper.selectProductById(id);
    }


    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectProductList(Product product) {
        return baseMapper.selectProductList(product);
    }

    /**
     * 查询商品Vo列表
     *
     * @param productVo
     * @return
     */
    @Override
    public List<ProductVo> selectProductVoList(ProductVo productVo) {

//        List<ProductVo> productVoList = new ArrayList<>();
        List<ProductVo> productVoList = baseMapper.selectProductVoList(productVo);
        ///设置每个商品的图片
        // 获取所有商品的id
        List<Long> productIdList = productVoList.stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        // 查询出所有商品的图片
        if (productIdList.size() > 0) {
            List<Picture> pictureList = pictureService.selectPictureListByItemIdListAndType(productIdList, PictureType.PRODUCT.getType());
            Map<Long, List<Picture>> itemIdAndPicList = new HashMap<>();
            for (Picture picture : pictureList) {
                if (!itemIdAndPicList.containsKey(picture.getItemId())) {
                    List<Picture> picList = new ArrayList<>();
                    picList.add(picture);
                    itemIdAndPicList.put(picture.getItemId(), picList);
                } else {
                    itemIdAndPicList.get(picture.getItemId()).add(picture);
                }
            }
            // 给每个商品设置图片
            for (ProductVo vo : productVoList) {
                vo.setPicList(itemIdAndPicList.get(vo.getId()));
            }
        }
        return productVoList;
    }

    @Override
    public ProductVo selectProductVoById(Long id) {
        return null;
    }

    /**
     * 将商品的阅读量加1
     *
     * @param id
     */
    @Override
    public void readNumPlusOne(Long id) {
        baseMapper.readNumPlusOne(id);
    }

    @Override
    public void starNumPlusOne(Long productId) {
        baseMapper.starNumPlusOne(productId);
    }

    @Override
    public void starNumDiffOne(Long productId) {
        baseMapper.starNumDiffOne(productId);
    }

    @Override
    public List<ProductVo>[] splitToTwoGroups(List<ProductVo> productVoList, Double sumAspectRatioOfColumn1, Double sumAspectRatioOfColumn2, Double messageAspectRatio) {
        List<ProductVo>[] resultArr = new List[2];
        for (int i = 0; i < resultArr.length; i++) {
            resultArr[i] = new ArrayList<>();
        }
        /// 数据准备
        // 获取每个图片的高宽比
        Map<Long, Double> idAndRatioMap = new HashMap<>();
        // 存储所有商品的id
        List<Long> idList = new ArrayList<>();
//        long start = System.currentTimeMillis();
        for (ProductVo productVo : productVoList) {
            idList.add(productVo.getId());
            if (productVo.getPicList() != null && productVo.getPicList().size() > 0) {
//                try {
//                    BufferedImage sourceImg = ImageIO.read(new URL(productVo.getPicList().get(0)).openStream());
//                    idAndRatioMap.put(productVo.getId(), sourceImg.getHeight() * 1.0 / sourceImg.getWidth());
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
                idAndRatioMap.put(productVo.getId(), productVo.getPicList().get(0).getAspectRatio());
            } else {
                idAndRatioMap.put(productVo.getId(), 0.0);
            }
        }
//        System.out.println("分组时间：" + (System.currentTimeMillis() - start) + "ms");

        /// 深度优先遍历，找出所有方案，选择两组高度差距最小的分组方案
        GroupDivide groupDivide = new GroupDivide();
        groupDivide.search(idList, idAndRatioMap, sumAspectRatioOfColumn1, sumAspectRatioOfColumn2, messageAspectRatio);

        /// 最后处理分组
        List<Long> group1 = groupDivide.bestGroup1;
        List<Long> group2 = new ArrayList<>();
        for (Long id : idList) {
            if (group1.indexOf(id) == -1) {
                group2.add(id);
            }
        }
        // 确保第一组的商品比第二组的商品多
        if (group1.size() > group2.size()) {
            for (ProductVo productVo : productVoList) {
                if (group1.indexOf(productVo.getId()) != -1) {
                    resultArr[0].add(productVo);
                } else {
                    resultArr[1].add(productVo);
                }
            }
        }else {
            for (ProductVo productVo : productVoList) {
                if (group1.indexOf(productVo.getId()) != -1) {
                    resultArr[1].add(productVo);
                } else {
                    resultArr[0].add(productVo);
                }
            }
        }
        return resultArr;
    }


    /**
     * 新增商品
     *
     * @param product 商品
     * @return 结果
     */
    @Override
    public int insertProduct(Product product) {
        product.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertProduct(product);
    }

    /**
     * 修改商品
     *
     * @param product 商品
     * @return 结果
     */
    @Override
    public int updateProduct(Product product) {
        product.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateProduct(product);
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteProductByIds(Long[] ids) {
        return baseMapper.deleteProductByIds(ids);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteProductById(Long id) {
        return baseMapper.deleteProductById(id);
    }


}
